package com.example.utils;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Component
public class FlowUtils {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    public boolean limitOnceCheck(String key, int blockTime) {
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))) {
            return false;
        } else {
            stringRedisTemplate.opsForValue().set(key, "", blockTime, TimeUnit.SECONDS);
            return true;
        }
    }

    //针对在时间段内多次请求，如3秒内限制请求20次，超出频率则封禁一段时间
    public boolean limitPeriodCounterCheck(String counterKey, int frequency, int period) {
        if (stringRedisTemplate.hasKey(counterKey)) {
            Long value = Optional.ofNullable(stringRedisTemplate.opsForValue().increment(counterKey)).orElse(0L);
            if (value > frequency) {
                stringRedisTemplate.expire(counterKey, period, TimeUnit.SECONDS);
                return false;
            }
        } else {
            stringRedisTemplate.opsForValue().set(counterKey, "1", period, TimeUnit.SECONDS);
        }
        return true;
    }
}
